package com.zxy.furns.web;/**
 * ClassName: FurnServlet
 * Package: com.zxy.furns.web
 *
 * @Author zxy
 * @Create 2025/3/21 15:02
 * @Version 1.0
 * title:
 * Description:
 */

import com.zxy.furns.entity.Cart;
import com.zxy.furns.entity.CartItem;
import com.zxy.furns.entity.Furn;
import com.zxy.furns.entity.Page;
import com.zxy.furns.service.FurnService;
import com.zxy.furns.service.impl.FurnServiceImpl;
import com.zxy.furns.utils.DataUtils;
import com.zxy.furns.utils.FurnDataCheckUtils;
import com.zxy.furns.utils.WebUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

@WebServlet("/manage/furnServlet")
public class FurnServlet extends BasicServlet {
    private FurnService furnService = new FurnServiceImpl();


    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Furn> furns = furnService.queryFurns();
        req.setAttribute("furns", furns);
        req.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(req, resp);
    }


    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Furn furn = DataUtils.copyParamToBean(req.getParameterMap(), new Furn());
        if (FurnDataCheckUtils.validateFurn(furn)) {
            furnService.addFurn(furn);
            resp.sendRedirect(req.getContextPath() + "/manage/furnServlet?action=page&pageNo=" + req.getParameter("pageNo"));

        }
    }


    protected void del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = DataUtils.parseInt(req.getParameter("id"), 0);
        furnService.delFurn(id);
        // 从请求参数中获取 pageNo

        resp.sendRedirect(req.getContextPath() + "/manage/furnServlet?action=page&pageNo=" + req.getParameter("pageNo"));
    }


    protected void showFurn(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = DataUtils.parseInt(req.getParameter("id"), 0);
        Furn furn = furnService.queryFurnById(id);
        req.setAttribute("furn", furn);
        // 从请求参数中获取 pageNo
        String pageNo = req.getParameter("pageNo");
        if (pageNo != null) {
            req.setAttribute("pageNo", pageNo);
        }
        // req.setAttribute("pageNo",req.getAttribute("pageNo"));
        req.getRequestDispatcher("/views/manage/furn_update.jsp").forward(req, resp);
    }


//    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        Furn furn = DataUtils.copyParamToBean(req.getParameterMap(), new Furn());
//        furnService.updateFurn(furn);
//
//        System.out.println("家具更新成功！");
//
////        resp.sendRedirect(req.getContextPath()+"/manage/furnServlet?action=list");
//
//        String pageNo = req.getParameter("pageNo");
//        System.out.println("请求重定向之前pageNo为: " + pageNo);
//        //这里选择分页
//        resp.sendRedirect(req.getContextPath() + "/manage/furnServlet?action=page&pageNo=" + req.getParameter("pageNo"));
//    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //如果我们的表单是enctype="multipart/form-data"
        //那么就得不到id了
        int id = DataUtils.parseInt(req.getParameter("id"), 0);
        //获取到对应的furn对象
        Furn furn = furnService.queryFurnById(id);
        //todo 做一个判断，furn为空就不处理
        req.setCharacterEncoding("utf-8");
        if (ServletFileUpload.isMultipartContent(req)) {
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            try {
                List<FileItem> list = servletFileUpload.parseRequest(req);
                for (FileItem fileItem : list) {
                    if (fileItem.isFormField()) {
                        if ("name".equals(fileItem.getFieldName())) {
                            furn.setName(fileItem.getString("UTF-8"));
                        } else if ("maker".equals(fileItem.getFieldName())) {
                            furn.setMaker(fileItem.getString("UTF-8"));
                        } else if ("price".equals(fileItem.getFieldName())) {
                            furn.setPrice(new BigDecimal(fileItem.getString("UTF-8")));
                        } else if ("sales".equals(fileItem.getFieldName())) {
                            furn.setSales(new Integer(fileItem.getString("UTF-8")));
                        } else if ("stock".equals(fileItem.getFieldName())) {
                            furn.setStock(new Integer(fileItem.getString("UTF-8")));
                        }
                    } else {
                        String name = fileItem.getName();
                        if (name != null || !name.isEmpty()) {
                            String filePath = "/" + WebUtils.FURN_IMG_DIRECTORY + "/";
                            String fileRealPath = req.getServletContext().getRealPath(filePath + WebUtils.getYearMonthDay());
                            File fileRealPathDirectory = new File(fileRealPath);
                            if (!fileRealPathDirectory.exists()) {
                                fileRealPathDirectory.mkdirs();
                            }
                            //防止文件上传同名覆盖的问题
                            name = UUID.randomUUID().toString() + "_" + System.currentTimeMillis()+"_"+name;
                            String fullFilePath = fileRealPathDirectory+"/"+name;
                            fileItem.write(new File(fullFilePath));
                            furn.setImgPath(WebUtils.FURN_IMG_DIRECTORY+WebUtils.getYearMonthDay()+"/"+name);

                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace(); // 打印详细错误信息
                throw new RuntimeException(e);
            }
        }

        furnService.updateFurn(furn);

        //可以请求转发到成功更新的页面
        req.getRequestDispatcher("/views/manage/update_ok.jsp").forward(req, resp);
    }

    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pageNo = DataUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = DataUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        Page<Furn> page = furnService.page(pageNo, pageSize);
        req.setAttribute("page", page);

        req.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(req, resp);
    }


}